package com.cnap.multiclouldmgmt.controller;

import com.cnap.multiclouldmgmt.config.TokenFilter;
import com.cnap.multiclouldmgmt.model.CommonResult;
import com.cnap.multiclouldmgmt.model.RepByPage;
import com.cnap.multiclouldmgmt.model.RepByPageWithDate;
import com.cnap.multiclouldmgmt.model.k8sModels.K8sClusterModel;
import com.cnap.multiclouldmgmt.model.log.OperationTypeEnum;
import com.cnap.multiclouldmgmt.model.privatecloud.PrivateVmCreateModel;
import com.cnap.multiclouldmgmt.scheduleTask.K8ClusterInfoScheduledTask;
import com.cnap.multiclouldmgmt.service.K8sClusterService;
import com.cnap.multiclouldmgmt.service.MultiCloudMgmtService;
import com.cnap.multiclouldmgmt.service.OperationLogService;
import com.cnap.multiclouldmgmt.service.VmResourceService;
import com.cnap.multiclouldmgmt.util.DateUtils;
import com.cnap.multiclouldmgmt.util.FileUtils;
import com.cnap.multiclouldmgmt.util.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 混合云网管理-混合云网管理
 * 用于集群注册，删除等操作
 * @author dyq
 */
@Api(tags ="混合云网管理-混合云网管理")
@RequestMapping(path = "/cnap/multicloudmgmt/v1/multiCloud")
@RestController
@ResponseBody
public class MultiCloudMgmtController {

    private final static Logger LOGGER = LoggerFactory.getLogger(MultiCloudMgmtController.class);

    @Autowired
    private MultiCloudMgmtService multiCloudMgmtService;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private K8sClusterService k8sClusterService;

    @Autowired
    private VmResourceService vmResourceService;
    /**
     * 根据条件获取集群列表
     * @param cloudVendor
     * @param k8sClusterName
     * @param pageSize
     * @param pageNo
     * @return
     */
    @ApiOperation(value = "1-1 根据条件获取集群列表",httpMethod = "GET",notes = "入参云供应商cloudVendor，选择集群的名称k8sClusterName")
    @RequestMapping(path = "/getK8sClusterInfos",method = RequestMethod.GET)
    public CommonResult<RepByPageWithDate<K8sClusterModel>> getK8sClusterInfos(String cloudVendor, String k8sClusterName, int pageSize, int pageNo,
                                                                               String k8sStatus,String accountName) {

        try {
            String createUser = TokenUtils.getUserName();
            RepByPage<K8sClusterModel> result =
                    multiCloudMgmtService.getK8sClusterInfos(cloudVendor,k8sClusterName,pageSize,pageNo,createUser,accountName);

            RepByPageWithDate<K8sClusterModel> resultWithDate = new RepByPageWithDate<K8sClusterModel>();
            Date recentDate = null;
            List<K8sClusterModel> k8sClusterModelsWithStatus = new ArrayList<>();

            if (result.getTotalNum() > 0){

                for (K8sClusterModel k8sClusterModel:result.getResult()){

                    if (recentDate == null){
                        recentDate = k8sClusterModel.getResfeshDate();
                    }else{

                        if (k8sClusterModel.getResfeshDate() != null){
                            if (k8sClusterModel.getResfeshDate().getTime() > recentDate.getTime()){
                                recentDate = k8sClusterModel.getResfeshDate();
                            }
                        }
                    }

                    if (StringUtils.isNotEmpty(k8sStatus)){

                        if (StringUtils.equalsIgnoreCase(k8sClusterModel.getStatus(),k8sStatus)){
                            k8sClusterModelsWithStatus.add(k8sClusterModel);
                        }

                    }
                }
            }

            if (recentDate == null){
                resultWithDate.setSyncTime(DateUtils.changeDateFormatYYYYMMDDHHMMSS(new Date()));
            }else {
                resultWithDate.setSyncTime(DateUtils.changeDateFormatYYYYMMDDHHMMSS(recentDate));

            }
            resultWithDate.setResult(result.getResult());
            if (StringUtils.isNotEmpty(k8sStatus)){
                resultWithDate.setResult(k8sClusterModelsWithStatus);
            }
            resultWithDate.setPageNo(result.getPageNo());
            resultWithDate.setTotalNum(result.getTotalNum());
            resultWithDate.setPageSize(result.getPageSize());
            resultWithDate.setOtherInfo(result.getOtherInfo());

            //根据条件获取集群列表
            return CommonResult.success(resultWithDate);

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController getK8sClusterInfos error pageNo={}",pageNo,e);

            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 注册一个集群
     * @param k8sConfigFile
     * @param cloudVendor
     * @param k8sClusterIp
     * @param k8sClusterName
     * @param k8sClusterDescribe
     * @param k8sClusterLocation
     * @param pmax
     * @param pidle
     * @return
     */
    @ApiOperation(value = "1-2 注册一个集群",httpMethod = "POST", notes = "注册一个集群")
    @RequestMapping(path = "/addK8sCluster",method = RequestMethod.POST)
    public CommonResult<Void> addK8sCluster(@RequestParam("k8sConfigFile") @ApiParam(value = "k8s的config文件")
                                                             MultipartFile k8sConfigFile,
                                                 @ApiParam(value = "集群服务商") String cloudVendor,
                                                 @ApiParam(value = "k8sClusterIp") String k8sClusterIp,
                                                 @ApiParam(value = "集群名称")String k8sClusterName,
                                                 @ApiParam(value = "集群描述")String k8sClusterDescribe,
                                                 @ApiParam(value="所属区域")String k8sClusterLocation,
                                                 @ApiParam(value="最大功率")String pmax,
                                                 @ApiParam(value="最大功率")String pidle) {
        try {

            //从请求中获取config的内容
            String configCotent = StringUtils.remove(FileUtils.getFileContent(k8sConfigFile),"\n");

            //构建数据库类型
            K8sClusterModel k8sClusterModel = new K8sClusterModel();
            k8sClusterModel.setK8sClusterLocation(k8sClusterLocation);
            k8sClusterModel.setK8sClusterName(k8sClusterName);
            k8sClusterModel.setCloudVendor(cloudVendor);
            k8sClusterModel.setCreateTime(new Date());
            k8sClusterModel.setK8sClusterConfig(configCotent);
            k8sClusterModel.setK8sClusterDescribe(k8sClusterDescribe);
            k8sClusterModel.setK8sClusterIp(k8sClusterIp);

            //新建集群
            multiCloudMgmtService.addK8sCluster(k8sClusterModel);

            //统一记录操作日志
            operationLogService.saveOperationLog(OperationTypeEnum.ADD.getType(),"注册新集群：" + k8sClusterName);

            return CommonResult.successMsg("addK8sClusterInfo success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController addK8sCluster error k8sClusterIp={}",k8sClusterIp,e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 注册一个集群通过token
     * @param k8sClusterModel
     * @return
     */
    @ApiOperation(value = "1-2-1 注册一个集群",httpMethod = "POST", notes = "注册一个集群")
    @RequestMapping(path = "/addK8sClusterByToken",method = RequestMethod.POST)
    public CommonResult<Void> addK8sClusterByToken(@RequestBody K8sClusterModel k8sClusterModel ) {
        try {

            //通过token注册集群
            multiCloudMgmtService.addK8sCluster(k8sClusterModel);

            //统一记录操作日志
            operationLogService.saveOperationLog(OperationTypeEnum.ADD.getType(), "注册新集群：" + k8sClusterModel.getK8sClusterName());

            return CommonResult.successMsg("addK8sClusterInfo success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController addK8sClusterByToken error k8sClusterIp={}",k8sClusterModel.getK8sClusterIp(),e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 编辑集群，根据服务商名和ip唯一确定一个集群
     * @param k8sClusterModel
     * @return
     */
    @ApiOperation(value = "1-3 编辑集群，根据服务商名和ip唯一确定一个集群",httpMethod = "PUT", notes = "编辑一个集群")
    @RequestMapping(path = "/editK8sClusterInfo",method = RequestMethod.PUT)
    public CommonResult<Void> editK8sClusterInfo(@RequestBody K8sClusterModel k8sClusterModel) {

        try {

            //编辑集群，根据服务商名和ip唯一确定一个集群
            multiCloudMgmtService.editK8sClusterInfo(k8sClusterModel);

            //统一记录操作日志
            operationLogService.saveOperationLog(OperationTypeEnum.OTHER.getType(), "编辑集群：" + k8sClusterModel.getK8sClusterName());

            return CommonResult.successMsg("editK8sClusterInfo success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController editK8sClusterInfo error k8sClusterIp={}",k8sClusterModel.getK8sClusterIp(),e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 删除集群，根据服务商名和ip唯一确定一个集群
     * @param cloudVendor
     * @param k8sClusterIp
     * @return
     */
    @ApiOperation(value = "1-4 删除集群，根据服务商名和ip唯一确定一个集群",httpMethod = "DELETE", notes = "删除集群")
    @RequestMapping(path = "/editK8sClusterInfo",method = RequestMethod.DELETE)
    public CommonResult<Void> delK8sCluster(@ApiParam(value = "集群服务商") String cloudVendor,
                                                 @ApiParam(value = "k8sClusterIp") String k8sClusterIp) {

        try {

            if (LOGGER.isInfoEnabled()){
                LOGGER.info("#########################################");
                LOGGER.info("delK8sCluster begin ip={}",k8sClusterIp);
            }

            //删除集群，根据服务商名和ip唯一确定一个集群
            multiCloudMgmtService.delK8sCluster(k8sClusterIp);

            //统一记录操作日志
            operationLogService.saveOperationLog(OperationTypeEnum.DELETE.getType(), "删除集群：" + k8sClusterIp);

            return CommonResult.successMsg("delK8sCluster success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController delK8sCluster error k8sClusterIp={}",k8sClusterIp,e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 刷新一个集群信息
     * @param k8sClusterIp
     * @return
     */
    @ApiOperation(value = "1-6 刷新一个集群信息",httpMethod = "GET", notes = "刷新集群")
    @RequestMapping(path = "/refeshK8sCluster",method = RequestMethod.GET)
    public CommonResult<Void> refeshK8sCluster(@ApiParam(value = "k8sClusterIp") String k8sClusterIp) {

        try {

            if (LOGGER.isInfoEnabled()){
                LOGGER.info("#########################################");
                LOGGER.info("refeshK8sCluster begin ip={}",k8sClusterIp);
            }

            k8sClusterService.refeshK8sClusterInfos(k8sClusterIp);

            return CommonResult.successMsg("refeshK8sCluster success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController refeshK8sCluster error k8sClusterIp={}",k8sClusterIp,e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 删除集群，根据ip唯一确定一个集群
     * @param k8sClusterIp
     * @return
     */
    @ApiOperation(value = "1-7 接触纳管",httpMethod = "DELETE", notes = "删除集群")
    @RequestMapping(path = "/deControlK8sCluster",method = RequestMethod.DELETE)
    public CommonResult<Void> deControlK8sCluster(@ApiParam(value = "k8sClusterIp") String k8sClusterIp) {

        try {

            if (LOGGER.isInfoEnabled()){
                LOGGER.info("#########################################");
                LOGGER.info("deControlK8sCluster begin ip={}",k8sClusterIp);
            }

            //解除纳管
            multiCloudMgmtService.deControlK8sCluster(k8sClusterIp);

            //统一记录操作日志
            operationLogService.saveOperationLog(OperationTypeEnum.DELETE.getType(), "解除纳管：" + k8sClusterIp);

            return CommonResult.successMsg("deControlK8sCluster success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController delK8sCluster error k8sClusterIp={}",k8sClusterIp,e);
            return CommonResult.failed(e.getMessage());
        }
    }


    /**
     * 注册一个集群通过token
     * @param privateVmCreateModel
     * @return
     */
    @ApiOperation(value = "1-5 一个已经开通的虚机，安装k8s等东西",httpMethod = "POST", notes = "注册一个集群")
    @RequestMapping(path = "/vmAddK8sCluster",method = RequestMethod.POST)
    public CommonResult<Void> vmAddK8sCluster(@RequestBody PrivateVmCreateModel privateVmCreateModel ) {
        try {

            String userName = TokenUtils.getUserName();

            privateVmCreateModel.setUserName(userName);
            vmResourceService.addVmK8sCluster(privateVmCreateModel);
            //统一记录操作日志
            operationLogService.saveOperationLog(OperationTypeEnum.ADD.getType(), "创建新集群：" + privateVmCreateModel.getExtranlIp());

            return CommonResult.successMsg("vmAddK8sCluster success");

        }catch (Exception e){

            LOGGER.error("MultiCloudMgmtController vmAddK8sCluster error k8sClusterIp={}",privateVmCreateModel.getExtranlIp(),e);
            return CommonResult.failed(e.getMessage());
        }
    }

}
